package Server.ExtComponents.MinaEngine.service;


import Server.ExtComponents.BaseConfig.config;
import Server.ExtComponents.MinaEngine.config.MServerConfig;
import Server.ExtComponents.utilsKit.PackageUtils;
import Server.ExtComponents.utilsKit.ProperTiesUtil;
import org.apache.log4j.xml.DOMConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Properties;


/**
 * @author :陈磊 <br/>
 * Date: 12-12-9<br/>
 * Time: 下午9:19<br/>
 * connectMethod:13638363871@163.com<br/>
 *  映射游戏数据包和处理逻辑函数
 *  添加到相应的数组中保存
 *  1.初始化逻辑处理函数引用对象
 *  2.注册处理的数据包和处理函数引用对象的映射关系
 *  3.反射处理加载
 */
@SuppressWarnings("unchecked")
public class MapperSocketPack {
    private  final Logger LOGGER = LoggerFactory.getLogger(MapperSocketPack.class);
   /****使用数组来存储数据包和处理函数的关系，通过数组下标索引来找到相应的操作处理函数的引用，注意，产生的实例引用时单例，所以是线程安全的**/
    public static final IController[] GAME_CONTROLLERS=new IController[255];//游戏数据包

    public static final IController[] NEGATIVE_GAME_CONTROLLERS=new IController[127];//监控系统数据包

    /**
     * 注册处理关系
     */
    public void addMapper() throws Exception {
        //通过反射，找到包路径下的class，返回类数组
        String[] ControllerClassNames = PackageUtils.findClassesInPackage(config.HANDLE_PACKAHE);
        Properties properties= ProperTiesUtil.getProPertis(config.CMD_CONFIG);
         //game pack
        for(String className : ControllerClassNames) {
                IController iController = (IController) Class.forName(className).newInstance();
                if(iController.AutoMapper()){
                    int i=Integer.parseInt(properties.getProperty(className.substring(className.lastIndexOf('.') + 1)));
                    if(i<0){  //-1 -- -59
                        NEGATIVE_GAME_CONTROLLERS[-i]=iController;
                        if (MServerConfig.DEBUG){
                            LOGGER.info(NEGATIVE_GAME_CONTROLLERS[-i]+":cmd---->"+properties.getProperty(className.substring(className.lastIndexOf('.') + 1)));
                        }
                    }else {
                        GAME_CONTROLLERS[i]=iController;
                        if (MServerConfig.DEBUG){
                            LOGGER.info(GAME_CONTROLLERS[i]+":cmd---->"+properties.getProperty(className.substring(className.lastIndexOf('.') + 1)));
                        }
                    }
                }
        }
        properties.clear();
    }

    public static void main(String[] args) throws Exception{
        DOMConfigurator.configure(config.Game_log4j);
        MapperSocketPack mapperSocketPack=new MapperSocketPack();
        mapperSocketPack.addMapper();
    }

}
